package com.yunxi.service.dubboService.impl.customer;

import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yunxi.baseDataToHub.pojo.urm.ClientInfoVO;
import com.yunxi.baseDataToHub.pojo.urm.IntentionalInformationVO;
import com.yunxi.baseDataToHub.pojo.urm.UserInfoVO;
import com.yunxi.baseDataToHub.service.urm.UrmDubboService;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.customer.pojo.CustomerLinkVO;
import com.yunxi.customer.pojo.CustomerVO;
import com.yunxi.customer.pojo.SatCustomerIntentionVO;
import com.yunxi.customer.service.CustomerDubboService;
import com.yunxi.customer.service.CustomerLinkDubboService;
import com.yunxi.dealer.pojo.ClientInfoVOFromURM;
import com.yunxi.dealer.pojo.PartnerVO;
import com.yunxi.hubToBaseData.pojo.CustomerVOURM;
import com.yunxi.hubToBaseData.service.URM2baseDataDubboService;
import com.yunxi.model.customer.Customer;
import com.yunxi.model.customer.SatCustomerIntention;
import com.yunxi.model.customer.SatCustomerIntentionHis;
import com.yunxi.model.dealer.Partner;
import com.yunxi.sat.pojo.PartnerCustomerVO;
import com.yunxi.sat.pojo.SatCustomerClueVO;
import com.yunxi.sat.service.PartnerCustomerDubboService;
import com.yunxi.sat.service.PartnerCustomerHisDubboService;
import com.yunxi.sat.service.SatCustomerClueDubboService;
import com.yunxi.service.localService.customer.CustomerService;
import com.yunxi.service.localService.customer.SatCustomerIntentionHisService;
import com.yunxi.service.localService.customer.SatCustomerIntentionService;
import com.yunxi.service.localService.dealer.PartnerService;
import com.yunxi.sys.pojo.StaffVO;
import com.yunxi.sys.pojo.UserVO;
import com.yunxi.sys.service.StaffDubboService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

/**
 * <p>
 * 客户信息 服务实现类
 * </p>
 *
 * @author
 * @since 2019-05-09
 */
public class CustomerDubboServiceImpl implements CustomerDubboService, URM2baseDataDubboService {

   private static final Logger logger = LoggerFactory.getLogger(CustomerDubboServiceImpl.class);

   @Autowired
   @Qualifier(value = "customerServiceImpl")
   CustomerService customerService;

   @Autowired
   @Qualifier(value = "satCustomerIntentionServiceImpl")
   SatCustomerIntentionService satCustomerIntentionService;

   @Autowired
   @Qualifier(value = "satCustomerIntentionHisServiceImpl")
   SatCustomerIntentionHisService satCustomerIntentionHisService;

   @Autowired
   PartnerCustomerDubboService partnerCustomerDubboServiceImpl;

   @Autowired
   PartnerCustomerHisDubboService partnerCustomerHisDubboServiceImpl;

   @Autowired
   StaffDubboService staffDubboServiceImpl;

   @Autowired
   CustomerLinkDubboService customerLinkDubboServiceImpl;

   @Autowired
   UrmDubboService urmDubboServiceImpl;

   @Autowired
   SatCustomerClueDubboService satCustomerClueDubboServiceImpl;

   @Value("${urm.switch}")
   private String is2URM;

   @Autowired
   @Qualifier(value = "partnerServiceImpl")
   PartnerService partnerService;

   @Override
   public CustomerVO getById(String id) throws InvocationTargetException, IllegalAccessException, Exception {
      Customer customer = customerService.getById(id);
      if (customer != null) {
         CustomerVO customerVO = new CustomerVO();
         BeanUtils.copyProperties(customer, customerVO);
         return customerVO;
      } else {
         throw new Exception("操作失败,无法根据id:" + id + "找到对应客户!");
      }
   }

   /**
    * 通过手机号获取客户信息
    *
    * @param phone
    * @return
    * @throws Exception
    */
   @Override
   @Transactional
   public ApiResult getCustomerByPhone(String phone, LoginInfo loginInfo) throws Exception {
       String currentUserStr = RpcContext.getContext().getAttachment("currentUser");
      if (StringUtils.isEmpty(phone)) return ResponseUtil.fail(-10,"请输入手机号");
      if (StringUtils.isEmpty(loginInfo.getPartnerCode())) return ResponseUtil.fail(-10,"渠道商编号为空");
      if (StringUtils.isEmpty(loginInfo.getUserCode())) return ResponseUtil.fail(-10,"账号为空");
      if (StringUtils.isEmpty(loginInfo.getRoleCode())) return ResponseUtil.fail(-10,"当前登陆角色为空");
      String partnerCode = null;
      if (StringUtils.isNotEmpty(loginInfo.getPartnerCode())) {
         partnerCode = loginInfo.getPartnerCode();
      }
      CustomerVO customerVO = customerService.getCustomerByPhone(phone, partnerCode);
      if (customerVO == null || StringUtils.isEmpty(customerVO.getCustomerId())) return ResponseUtil.fail(-1, "没有该客户");
//      if (customerVO == null || StringUtils.isEmpty(customerVO.getCustomerId())) {
//         if ("true".equals(is2URM)) {
//            //根据手机号查询 URM客户信息
//            UserInfoVO userInfoVO = new UserInfoVO();
//            userInfoVO.setMobile(phone);
//            userInfoVO.setPartnerCode(partnerCode);
//            ApiResult apiResult = urmDubboServiceImpl.selectAccountByMobilePMS2Urm(userInfoVO);
//            if (apiResult.getData() == null) return ResponseUtil.fail(-1, "没有该客户");
//            if (200 != apiResult.getCode()) {
//               logger.error("URM接口执行，查询客户失败");
//               return ResponseUtil.fail(-10, "URM执行，查询客户失败");
//            }
//            if (apiResult.getData() != null) {
//               ClientInfoVOFromURM clientInfoVOFromURM = JSON.parseObject((String) apiResult.getData(), ClientInfoVOFromURM.class);
//               CustomerVO custVO = new CustomerVO();
//               setURMCustomerInfo2CustomerVO(custVO, clientInfoVOFromURM);
//               Customer customer = new Customer();
//               BeanUtils.copyProperties(custVO,customer);
//               customer.setPhone(phone);
//               customer.setCustStatus(0);
//
//               QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
//               HashMap<String, Object> map = new HashMap<>();
//               map.put("PHONE",phone);
//               map.put("PARTNER_CODE",loginInfo.getPartnerCode());
//               queryWrapper.allEq(map);
//               List<Customer> list = customerService.list(queryWrapper);
//               if (list!=null && list.size()>0){
//                  if (!loginInfo.getUserCode().equals(list.get(0).getSalesConsultantNo())) {
//                     UserVO userVO = new UserVO();
//                     userVO.setUserCode(list.get(0).getSalesConsultantNo());
//                     StaffVO staffVO = staffDubboServiceImpl.getByUser(userVO);
//                     customerVO.setStaffName(staffVO.getStaffName());
//                     return ResponseUtil.fail(-2, "该客户为" + staffVO.getStaffName() + "的客户,无法接待", customerVO);
//                  }
//               }else {
//                  customer.setSalesConsultantNo(loginInfo.getUserCode());
//                  customer.setPartnerCode(loginInfo.getPartnerCode());
//                  customer.setCreateBy(loginInfo.getUserCode());
//                  RpcContext.getContext().setAttachment("currentUser", currentUserStr);
//                   logger.debug(""+customer.getCreateBy());
//                  customerService.save(customer);
//               }
//            }
//            return ResponseUtil.fail(-1, "没有该客户");
//         } else {
//            List<CustomerVO> customerUrmList = customerService.getCustomerURM(phone);
//            if (customerUrmList!=null && customerUrmList.size()>0){
//               customerVO = customerUrmList.get(0);
//            }else {
//               return ResponseUtil.fail(-1, "没有该客户");
//            }
//         }
//      }
         if (DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())) {//销售顾问
               if (!loginInfo.getUserCode().equals(customerVO.getSalesConsultantNo()) && customerVO.getPartnerCode().equals(partnerCode)) {
                  UserVO userVO = new UserVO();
                  userVO.setUserCode(customerVO.getSalesConsultantNo());
                  StaffVO staffVO = staffDubboServiceImpl.getByUser(userVO);
                  customerVO.setStaffName(staffVO.getStaffName());
                  return ResponseUtil.fail(-2, "该客户为" + staffVO.getStaffName() + "的客户,无法接待", customerVO);
               }
            }

      return ResponseUtil.ok(customerVO);
   }

   private CustomerVO setURMCustomerInfo2CustomerVO(CustomerVO custVO, ClientInfoVOFromURM clientInfoVOFromURM) {
      //      custVO.setCustomerId();
      if (clientInfoVOFromURM.getId() != null) {
         custVO.setCustomerNo(String.valueOf(clientInfoVOFromURM.getId()));//客户编号
      }
      custVO.setPhone(clientInfoVOFromURM.getMobile());//手机号
      custVO.setName(clientInfoVOFromURM.getName());//姓名
      custVO.setSex(String.valueOf(clientInfoVOFromURM.getSex()));//性别
      custVO.setPartnerCode(clientInfoVOFromURM.getAgency());//供应商
      custVO.setSalesConsultantNo(clientInfoVOFromURM.getSalesConsultant());//销售顾问
      if (clientInfoVOFromURM.getBigRegion() != null) {
         custVO.setBigRegion(String.valueOf(clientInfoVOFromURM.getBigRegion()));//大区
      }
      custVO.setProvince(clientInfoVOFromURM.getRegProvince());//省
      custVO.setCity(clientInfoVOFromURM.getRegCity());//市
      custVO.setRegion(clientInfoVOFromURM.getRegStrict());//区
      custVO.setAddr(clientInfoVOFromURM.getAddress());//地址
      custVO.setCustomerType(String.valueOf(clientInfoVOFromURM.getUserType()));//客户类型
      custVO.setIntentionLev(clientInfoVOFromURM.getIntentionLevel());//意向级别
      custVO.setProfession(clientInfoVOFromURM.getProfession());//职业
      custVO.setDuty(clientInfoVOFromURM.getDuty());//职位
      custVO.setEducation(clientInfoVOFromURM.getEducation());//学历
      custVO.setAnnualIncome(clientInfoVOFromURM.getAnnualIncome());//年收入
      custVO.setMaritalStatus(clientInfoVOFromURM.getMaritalStatus());//婚姻状态 0：未识别，1：已婚，2：未婚
      custVO.setChildNum(clientInfoVOFromURM.getChildNum());//孩子数量
      custVO.setChild1Age(clientInfoVOFromURM.getChild1Age());//子女1的年龄
      custVO.setChild2Age(clientInfoVOFromURM.getChild2Age());//子女2的年龄
      custVO.setPurchaseIntention(clientInfoVOFromURM.getPurchaseIntention());//购买意向 0,未识别 1,近3个月需要购车 2, 近半年内需要购车 3, 近1年内需要购车 4, 近2年内需要购车 5, 考虑要买车
      custVO.setVehiclePersonnelStructure(clientInfoVOFromURM.getVehiclePersonnelStructure());//用车人员结构 0,未识别 1,1人 2,2人 3,3人 4,4人 5,5人 6,6人 7,7人 8,7人+
      custVO.setVehicleScene(clientInfoVOFromURM.getVehicleScene());//用车场景 0, 未识别 1,上班 2, 家庭出行 3, 旅游自驾 4, 出租接客 100, 其他
      custVO.setUser(String.valueOf(clientInfoVOFromURM.getDriver()));//驾驶人 0, 未识别 1, 自己 2, 伴侣 3, 父母 4, 其他
      custVO.setServiceSensitivity(clientInfoVOFromURM.getServiceSensitivity());//服务敏感度 分为1-10等级
      custVO.setVehicleKnowledgeProfessional(clientInfoVOFromURM.getVehicleKnowledgeProfessional());//汽车知识专业度 分为1-10等级
      custVO.setCarConcerns(clientInfoVOFromURM.getCarConcerns());//关注点
      custVO.setFamilyVehiclesNum(clientInfoVOFromURM.getFamilyVehiclesNum());//家庭车辆数量
      custVO.setFamilyVehicleBrand(clientInfoVOFromURM.getFamilyVehicleBrand());//家庭车辆品牌，多个使用逗号隔开
      custVO.setUserSource1(clientInfoVOFromURM.getUserSource_1());
      custVO.setUserSource2(clientInfoVOFromURM.getUserSource_2());
      custVO.setUserSource3(clientInfoVOFromURM.getUserSource_3());

      SatCustomerIntentionVO satCustomerIntentionVO = new SatCustomerIntentionVO();
      if (clientInfoVOFromURM.getIntentionalPurchasePrice() != null) {
         satCustomerIntentionVO.setIntentionalPrice(BigDecimal.valueOf(clientInfoVOFromURM.getIntentionalPurchasePrice()));//意向购车价格 1,10万以下 2,10-15万 3,15-20万 4,20-25万 5,25-30万 6,30万以上
      }
      custVO.setSatCustomerIntentionVO(satCustomerIntentionVO);
      return custVO;
   }

   private String getNum() {
      String numStr = "";
      String trandStr = String.valueOf((Math.random() * 9 + 1) * 10000);
      String dataStr = new SimpleDateFormat("yyyyMMddHHMMSS").format(new Date());
      numStr = trandStr.toString().substring(0, 3);
      numStr = numStr + dataStr;
      return numStr;
   }

   @Override
   @Transactional
   public ApiResult saveOrUpdate(CustomerVO customerVO, LoginInfo loginInfo) throws InvocationTargetException, IllegalAccessException, Exception {
      ApiResult apiResult = null;

      if (StringUtils.isEmpty(loginInfo.getUserCode())) return ResponseUtil.fail(-1,"登陆账号为空");
      if (StringUtils.isEmpty(loginInfo.getPartnerCode())) return ResponseUtil.fail(-1,"渠道商编号为空");
      if (StringUtils.isEmpty(customerVO.getPhone())) return ResponseUtil.fail(-1,"手机号为空");
      String partnerCode = loginInfo.getPartnerCode();
      customerVO.setPartnerCode(partnerCode);

      //通过手机号和渠道商code查询客户
      List<Customer> customerList = getCustomerListByPhoneAndPartnerCode(customerVO, loginInfo);
      if (customerList!=null && customerList.size()>0){
         customerVO.setCustomerNo(customerList.get(0).getCustomerNo());
         customerVO.setCustomerId(customerList.get(0).getCustomerId());
         customerVO.setSalesConsultantNo(customerList.get(0).getSalesConsultantNo());
      }else {
         customerVO.setSalesConsultantNo(loginInfo.getUserCode());
         if ("true".equals(is2URM)) {
            //根据手机号查询 URM客户信息
            apiResult = queryUrmCustomerInfoByPhone(customerVO, partnerCode);
            if (apiResult.getCode()!=200) return apiResult;
            ClientInfoVOFromURM clientInfoVOFromURM = JSON.parseObject((String) apiResult.getData(), ClientInfoVOFromURM.class);
            if (clientInfoVOFromURM.getId()!=null){
               customerVO.setCustomerNo(String.valueOf(clientInfoVOFromURM.getId()));
            }else {
               return ResponseUtil.fail(-1,"根据手机号查询 URM客户信息返回客户id为空");
            }
         }else {
            List<CustomerVO> customerUrmList = customerService.getCustomerURM(customerVO.getPhone());
            if (customerUrmList!=null && customerUrmList.size()>0){
               customerVO.setCustomerNo(customerUrmList.get(0).getCustomerNo());
            }else {
               return ResponseUtil.fail(-1,"该手机号不存在客户编号,待URM提供导入数据");
//               customerVO.setCustomerNo(getNum());
            }
         }
      }

      //同步客户信息到CRM
      String ordercustomerNoURM = null;
      if ("true".equals(is2URM)) {
         if (StringUtils.isNotEmpty(customerVO.getCustomerNo())) {
            boolean integer = isInteger(customerVO.getCustomerNo());
            if (integer == false) return ResponseUtil.fail(-1, "customerNo客户编号CRM:不是为纯数字");
         }
         apiResult = sendCustomer2URM(customerVO);
      }
      //维护客户基本信息
      Customer customer = saveCustomerInfo(customerVO, loginInfo);

      //维护渠道客户销售顾问关系
//      savePartnerCustomer(customerVO, loginInfo);

      //维护客户意向,意向历史
      saveCustomerIntention(customerVO, customer, loginInfo);
      if (apiResult != null && apiResult.getCode() != 200) {
         return apiResult;
      }
      return ResponseUtil.ok(customerVO.getCustomerNo());
   }

   private List<Customer> getCustomerListByPhoneAndPartnerCode(CustomerVO customerVO, LoginInfo loginInfo) {
      QueryWrapper<Customer> wrapper = new QueryWrapper<>();
      HashMap<String, Object> hashMap = new HashMap<>();
      hashMap.put("PHONE",customerVO.getPhone());
      hashMap.put("PARTNER_CODE",loginInfo.getPartnerCode());
      wrapper.allEq(hashMap);
      return customerService.list(wrapper);
   }

   private ApiResult queryUrmCustomerInfoByPhone(CustomerVO customerVO, String partnerCode) {
      UserInfoVO userInfoVO = new UserInfoVO();
      userInfoVO.setMobile(customerVO.getPhone());
      userInfoVO.setPartnerCode(partnerCode);
      ApiResult result = urmDubboServiceImpl.selectAccountByMobilePMS2Urm(userInfoVO);
      //Guan 内部已返回报错信息无需重新判断
      /*
      if (result.getData() == null) {
          result = ResponseUtil.fail(-1, "没有该客户");
      }
      if (200 != result.getCode()) {
          logger.error("URM接口执行，查询客户失败");
          result =  ResponseUtil.fail(-10, "URM执行，查询客户失败");
      }
       */
      return result;
   }

   private ApiResult sendCustomer2URM(CustomerVO customerVO) {
      ClientInfoVO clientInfoVO = setURMClientInfoVO(customerVO);
      ApiResult apiResult = null;
      String string = null;
      try {
         apiResult = urmDubboServiceImpl.sendClientInfoPMS2Urm(clientInfoVO);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         e.printStackTrace();
         logger.error("URM接口调用失败，同步客户信息sendCustomer2URM" + e.getMessage());
      }
      if (200 == apiResult.getCode()) {
         Object data = apiResult.getData();
         if (data != null) {
            string = JSON.toJSONString(data);
            logger.debug("URM接口调用获取客户编号:+++++++" + string);
         }
      } else {
         logger.error("URM接口执行失败，同步客户信息sendCustomer2URM");
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }
      return apiResult;
   }

   public static boolean isInteger(String str) {
      Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
      return pattern.matcher(str).matches();
   }

   private ClientInfoVO setURMClientInfoVO(CustomerVO customerVO) {
      ClientInfoVO clientInfoVO = new ClientInfoVO();
      if (customerVO.getCustomerNo() != null) {
         clientInfoVO.setId(Long.valueOf(customerVO.getCustomerNo()));
      }
      clientInfoVO.setMobile(customerVO.getPhone());
      clientInfoVO.setName(customerVO.getName());
      if (StringUtils.isNotEmpty(customerVO.getSex())) {
         clientInfoVO.setSex(Integer.parseInt(customerVO.getSex()));
      }
      if (customerVO.getBirthDay() != null) {
         clientInfoVO.setBirthday(new SimpleDateFormat("yyyy-MM-dd").format(customerVO.getBirthDay()));
      }
      clientInfoVO.setIdCard(customerVO.getIdCertNo());//身份证号
      clientInfoVO.setEmail(customerVO.getEmail());
      if (customerVO.getAge() != null) {
         clientInfoVO.setAge(customerVO.getAge());
      }
      clientInfoVO.setBigRegion(0);//大区  0:"未识别"，1, "南区"，2, "北区"
      clientInfoVO.setZipCode(customerVO.getPostcode());//邮编
      clientInfoVO.setRegProvince(customerVO.getProvince());//注册的省
      clientInfoVO.setRegCity(customerVO.getCity());
      clientInfoVO.setRegStrict(customerVO.getRegion());
      clientInfoVO.setAddress(customerVO.getAddr());
      clientInfoVO.setRegTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
      if (StringUtils.isNotEmpty(customerVO.getCustomerType())) {
         clientInfoVO.setUserType(Integer.parseInt((customerVO.getCustomerType())));//用户类型 1, "车主"，2, "线索"，6, "潜客"
      }
      if (customerVO.getSource() != null) {
         clientInfoVO.setUserSource(Integer.parseInt(String.valueOf(customerVO.getSource())));//用户来源
      }
      clientInfoVO.setUserSourceSecond("");//用户的二级来源
      if (StringUtils.isEmpty(customerVO.getCustomerId())) {
         clientInfoVO.setOptionType(1);//操作类型 1：插入 2 ：更新
      } else {
         clientInfoVO.setOptionType(2);//操作类型 1：插入 2 ：更新
      }
      clientInfoVO.setPartnerCode(customerVO.getPartnerCode());
      QueryWrapper<Partner> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("PARTNER_CODE", customerVO.getPartnerCode());
      Partner one = partnerService.getOne(queryWrapper);
      clientInfoVO.setPartnerName(one.getPartnerName());
      return clientInfoVO;
   }

   /**
    * 维护客户基本信息
    *
    * @param customerVO
    * @param loginInfo
    * @return
    * @throws InvocationTargetException
    * @throws IllegalAccessException
    */
   private Customer saveCustomerInfo(CustomerVO customerVO, LoginInfo loginInfo) throws InvocationTargetException, IllegalAccessException {

      if (StringUtils.isEmpty(customerVO.getCustomerId())) {
         //是否线索跳转创建客户
         if (StringUtils.isNotEmpty(customerVO.getClueId())) {
            satCustomerClueDubboServiceImpl.updateIsCreatedCust(customerVO.getClueId());
            if ("3".equals(customerVO.getClueType())) {//订单客户
               customerVO.setCustStatus(1);//0意向 1订单 2战败 3基盘 4线索
               customerVO.setLevel("1");
            } else {
               customerVO.setCustStatus(0);//0意向 1订单 2战败 3基盘 4线索
               customerVO.setLevel("5");
            }
         } else {
            customerVO.setCustStatus(0);//0意向 1订单 2战败 3基盘 4线索
            if (StringUtils.isEmpty(customerVO.getLevel())) customerVO.setLevel("4");
         }

         customerVO.setTenantId(loginInfo.getTenantId());
         customerVO.setCreateBy(loginInfo.getUserCode());
      } else {
         customerVO.setUpdateBy(loginInfo.getUserCode());
      }

      QueryWrapper<Customer> wrapper = new QueryWrapper<>();
      wrapper.eq("CUSTOMER_NO",customerVO.getCustomerNo());
      wrapper.eq("PARTNER_CODE",customerVO.getPartnerCode());
      List<Customer> list = customerService.list(wrapper);
      if (list!=null && list.size()>0) {
         customerVO.setSource(list.get(0).getSource());
      }
      Customer customer = new Customer();
      BeanUtils.copyProperties(customerVO, customer);
      customerService.saveOrUpdate(customer);

      if (customerVO.getCustomerLinkVOList() != null && customerVO.getCustomerLinkVOList().size() > 0) {
         for (CustomerLinkVO customerLinkVO : customerVO.getCustomerLinkVOList()) {
            customerLinkVO.setCustomerNo(customerVO.getCustomerNo());
            customerLinkVO.setPartnerCode(customerVO.getPartnerCode());
            customerLinkDubboServiceImpl.saveOrUpdate(customerLinkVO);
         }
      }
      return customer;
   }


   /**
    * 维护渠道客户销售顾问关系表
    *
    * @param customerVO
    * @param loginInfo
    * @throws Exception
    */
   private void savePartnerCustomer(CustomerVO customerVO, LoginInfo loginInfo) throws Exception {
      PartnerCustomerVO partnerCustomerVO = new PartnerCustomerVO();
      if (loginInfo.getPartner() != null) {
         PartnerVO partnerVO = JSONObject.parseObject(JSONObject.toJSONString(loginInfo.getPartner()), PartnerVO.class);
         partnerCustomerVO.setPartnerCode(partnerVO.getPartnerCode());
         partnerCustomerVO.setSalesConsultantNo(loginInfo.getUserCode());
         partnerCustomerVO.setCustomerNo(customerVO.getCustomerNo());
         if (StringUtils.isEmpty(customerVO.getCustomerId())) {
            partnerCustomerVO.setCreateBy(loginInfo.getUserCode());
         } else {
            List<PartnerCustomerVO> list = partnerCustomerDubboServiceImpl.listByVo(partnerCustomerVO);
            if (list != null && list.size() > 0) {
               PartnerCustomerVO vo = list.get(0);
//            vo.setUpdateBy(loginInfo.getUserCode());

//            PartnerCustomerHisVO partnerCustomerHisVO = new PartnerCustomerHisVO();
//            BeanUtils.copyProperties(vo,partnerCustomerHisVO);
//            partnerCustomerHisDubboServiceImpl.saveOrUpdate(partnerCustomerHisVO,loginInfo);

//            partnerCustomerVO.setUpdateBy(loginInfo.getUserCode());
               partnerCustomerVO.setPartnerCustomerId(vo.getPartnerCustomerId());
            }
         }
         partnerCustomerDubboServiceImpl.saveOrUpdate(partnerCustomerVO, loginInfo);
      }
   }

   /**
    * 维护客户意向,意向历史
    *
    * @param customerVO
    * @param
    * @param customer
    */
   private ApiResult saveCustomerIntention(CustomerVO customerVO, Customer customer, LoginInfo loginInfo) throws Exception {
      ApiResult apiResult = null;
      SatCustomerIntentionVO satCustomerIntentionVO = customerVO.getSatCustomerIntentionVO();
      satCustomerIntentionVO.setCustomerNo(customerVO.getCustomerNo());
      satCustomerIntentionVO.setPartnerCode(loginInfo.getPartnerCode());

      QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
      HashMap<String, Object> map = new HashMap<>();
      map.put("CUSTOMER_NO",customerVO.getCustomerNo());
      map.put("PARTNER_CODE",loginInfo.getPartnerCode());
      queryWrapper.allEq(map);
      Customer customer1 = customerService.getOne(queryWrapper);
      satCustomerIntentionVO.setCustomerName(customer1.getName());
      satCustomerIntentionVO.setLevel(customer1.getLevel());
      //客户编号,客户姓名,客户级别,内饰色,外饰色,配置代码,车辆名
      if (StringUtils.isEmpty(customerVO.getCustomerId())) {
         satCustomerIntentionVO.setCreateBy(loginInfo.getUserCode());
      } else {
         satCustomerIntentionVO.setUpdateBy(loginInfo.getUserCode());

         QueryWrapper<SatCustomerIntention> wrapper = new QueryWrapper<>();
         HashMap<String, Object> map2 = new HashMap<>();
         map2.put("CUSTOMER_NO",customerVO.getCustomerNo());
         map2.put("PARTNER_CODE",loginInfo.getPartnerCode());
         wrapper.allEq(map2);
         SatCustomerIntention one = satCustomerIntentionService.getOne(wrapper);
         if (one != null) {
//         satCustomerIntention = one;
            satCustomerIntentionVO.setIntentionId(one.getIntentionId());
         }
      }
      String vehicleName = customerService.getVehicleNameByVehicleCode(satCustomerIntentionVO.getCatalogCode());
      satCustomerIntentionVO.setVehicleName(vehicleName);

      //线索编号,线索类型,渠道编号,客户编号
//      satCustomerIntention.setCreateBy(loginInfo.getUserCode());
      if (customer1.getSource()==1){
         SatCustomerIntentionVO customerClueInfo = customerService.getCustomerClueInfo(satCustomerIntentionVO);
         if (customerClueInfo != null) {
            satCustomerIntentionVO.setClueNo(customerClueInfo.getClueNo());
            satCustomerIntentionVO.setClueType(customerClueInfo.getClueType());
         }
      }


      SatCustomerIntention satCustomerIntention = new SatCustomerIntention();
      BeanUtils.copyProperties(satCustomerIntentionVO, satCustomerIntention);
      satCustomerIntentionService.saveOrUpdate(satCustomerIntention);

      //设置URM客户意向信息字段
      IntentionalInformationVO intentionalInformationVO = setIntentionURM(satCustomerIntentionVO,customer1);
      //发送客户意向信息到URM
      if ("true".equals(is2URM)) {
         apiResult = sendIntention2URM(intentionalInformationVO);
      }
      //意向历史
      if (StringUtils.isNotEmpty(customerVO.getCustomerId())) {
         SatCustomerIntentionHis satCustomerIntentionHis = new SatCustomerIntentionHis();
         BeanUtils.copyProperties(satCustomerIntention, satCustomerIntentionHis);
         satCustomerIntentionHisService.saveOrUpdate(satCustomerIntentionHis);
      }
      return apiResult;
   }

   private IntentionalInformationVO setIntentionURM(SatCustomerIntentionVO satCustomerIntentionVO,Customer customer) {
      IntentionalInformationVO intentionalInformationVO = new IntentionalInformationVO();
      intentionalInformationVO.setClueNo(satCustomerIntentionVO.getClueNo());//线索编号
      intentionalInformationVO.setClueType(satCustomerIntentionService.queryDictCn("Customer_ClueType", satCustomerIntentionVO.getClueType()));//线索类型
      intentionalInformationVO.setPartnerCode(satCustomerIntentionVO.getPartnerCode());//渠道编号
      intentionalInformationVO.setCustomerNo(satCustomerIntentionVO.getCustomerNo());//客户ID
      intentionalInformationVO.setCustomerName(satCustomerIntentionVO.getCustomerName());//客户姓名
      intentionalInformationVO.setVehicleCode(satCustomerIntentionVO.getCatalogCode());//15位码
      intentionalInformationVO.setIntentModel(satCustomerIntentionVO.getCatalogCode());//15位码
      intentionalInformationVO.setColorInCode(satCustomerIntentionVO.getColorInCode());//内饰颜色代码
      intentionalInformationVO.setColorInName(satCustomerIntentionVO.getColorInName());//内饰颜色名称
      intentionalInformationVO.setColorOutCode(satCustomerIntentionVO.getColorOutCode());//外饰颜色代码
      intentionalInformationVO.setColorOutName(satCustomerIntentionVO.getColorOutName());//外饰颜色名称
//      intentionalInformationVO.setLevel(satCustomerIntentionVO.getLevel());//客户级别
      intentionalInformationVO.setLevel(satCustomerIntentionService.queryDictCn("Customer_IntentionLevel", satCustomerIntentionVO.getLevel()));//客户级别
       intentionalInformationVO.setTel(customer.getPhone());//手机号
       intentionalInformationVO.setProvince(customer.getProvince());//省
       intentionalInformationVO.setCity(customer.getCity());//市
       intentionalInformationVO.setRegion(customer.getRegion());//县
       intentionalInformationVO.setSalAdviserCode(customer.getSalesConsultantNo());//展厅销售顾问
       intentionalInformationVO.setSex(customer.getSex());//性别

       //查询线索
      if (StringUtils.isNotEmpty(satCustomerIntentionVO.getClueNo())) {
         SatCustomerClueVO satCustomerClueVO = satCustomerIntentionService.getClueInfoByNo(satCustomerIntentionVO.getClueNo());
         if (satCustomerClueVO != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (satCustomerClueVO.getCreateTime() != null) {
               String format = simpleDateFormat.format(satCustomerClueVO.getCreateTime());
               intentionalInformationVO.setGetDate(format);//获取时间
            }
//            intentionalInformationVO.setIsGet(satCustomerIntentionService.queryDictCn("Clue_GetStatus", satCustomerClueVO.getIsGet().toString()));//线索状态(Clue_GetStatus,0未领取,1已领取,2超时)
            intentionalInformationVO.setIsGet(satCustomerClueVO.getIsGet().toString());//线索状态(Clue_GetStatus,0未领取,1已领取,2超时)
            intentionalInformationVO.setGetUser(satCustomerClueVO.getGetUser());//领取人
            if (satCustomerClueVO.getStatus() != null) {
               intentionalInformationVO.setStatus(satCustomerClueVO.getStatus());//状态1启用0禁用
            }
            if (satCustomerClueVO.getIsDel() != null) {
               intentionalInformationVO.setIsDel(satCustomerClueVO.getIsDel());//是否删除
            }
            intentionalInformationVO.setMemo(satCustomerClueVO.getMemo());//备注
            intentionalInformationVO.setAssignUser(satCustomerClueVO.getAssignUser());//分配人

            intentionalInformationVO.setIsSelf(satCustomerClueVO.getIsSelf());//是否自己领取
            intentionalInformationVO.setClueSource(satCustomerClueVO.getClueSource());//线索来源
            intentionalInformationVO.setSeries(satCustomerClueVO.getSeries());//车系
//            intentionalInformationVO.setIntentModel(satCustomerClueVO.getIntentModel());//车型
            intentionalInformationVO.setGetInfoWay(satCustomerClueVO.getGetInfoWay());//获取信息途径
//            intentionalInformationVO.setLevel(satCustomerIntentionService.queryDictCn("Customer_IntentionLevel", satCustomerClueVO.getLevel()));//意向级别
         }
      }
      return intentionalInformationVO;
   }

   private ApiResult sendIntention2URM(IntentionalInformationVO intentionalInformationVO) throws Exception {
      ApiResult apiResult = null;
      try {
         apiResult = urmDubboServiceImpl.sendIntentionalInformationPMS2Urm(intentionalInformationVO);
      } catch (Exception e) {
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         e.printStackTrace();
      }
      if (200 != apiResult.getCode()) {
         logger.error("URM接口执行，同步客户意向信息失败，事务回滚!");
         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         throw new Exception("URM接口执行，同步客户意向信息失败"+apiResult.getMsg());
      }
      if (apiResult.getData() != null) {
         JSON.parseObject((String) apiResult.getData());
      }
      return apiResult;
   }

   /**
    * 校验手机号是否重复
    *
    * @param customerVO
    * @throws Exception
    */
   private void checkPhoneIsExist(CustomerVO customerVO, LoginInfo loginInfo) throws Exception {
      String partnerCode = null;
      if (loginInfo.getPartner() != null) {
         partnerCode = JSONObject.parseObject(JSONObject.toJSONString(loginInfo.getPartner()), PartnerVO.class).getPartnerCode();
      }
      QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
      HashMap<String, String> map = new HashMap<>();
      map.put("PHONE", customerVO.getPhone());
      if (StringUtils.isEmpty(partnerCode)) {
         map.put("PARTNER_CODE", customerVO.getPartnerCode());
      } else {
         map.put("PARTNER_CODE", partnerCode);
      }
      queryWrapper.allEq(map);
      List<Customer> list = customerService.list(queryWrapper);
      if (list != null && list.size() > 0) {
         throw new Exception("操作失败,手机号:" + customerVO.getPhone() + "已存在!");
      }
   }

   @Override
   public void removeById(String id) {
      customerService.removeById(id);
   }

   public PageInfo<CustomerVO> findPageByVO(CustomerVO customerVO, Integer pageNum, Integer pageSize, LoginInfo loginInfo) throws InvocationTargetException, IllegalAccessException {
      if (loginInfo.getPartner() != null) {
         PartnerVO partnerVO = JSONObject.parseObject(JSONObject.toJSONString(loginInfo.getPartner()), PartnerVO.class);
         customerVO.setPartnerCode(partnerVO.getPartnerCode());
         if (loginInfo.getStaff() != null) {


            if (DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())) {
               customerVO.setSalesConsultantNo(loginInfo.getUserCode());
            }

            if (DictConstant.USER_ROLE_MANAGER.equals(loginInfo.getRoleCode())) {
               customerVO.setSalesConsultantNo("");
            }
            /*
            if ("ZW0801".equals(staffVO.getPositionCode())) {//销售顾问
               customerVO.setSalesConsultantNo(loginInfo.getUserCode());
            }
            if ("ZW0802".equals(staffVO.getPositionCode())) {//销售顾问销售经理
               customerVO.setSalesConsultantNo("");
            }*/
         }
      } else {
         customerVO.setPartnerCode("");
         customerVO.setSalesConsultantNo("");
      }
      return customerService.pageByVo(customerVO, pageNum, pageSize);
   }

   @Override
   public CustomerVO load(String customerNo,String partnerCode, LoginInfo loginInfo) {
      if (StringUtils.isNotEmpty(loginInfo.getPartnerCode())){
         partnerCode = loginInfo.getPartnerCode();
      }
      return customerService.load(customerNo, partnerCode);
   }

   @Override
   public void removeByListVo(List<CustomerVO> customerVOList) throws IllegalAccessException, InvocationTargetException, InstantiationException {
      customerService.removeByListVo(customerVOList);
   }


   /**
    * 今日新增客户
    *
    * @param customerVO
    * @param loginInfo
    * @return
    * @throws Exception
    */
   @Override
   public List<CustomerVO> todayCustomerList(CustomerVO customerVO, LoginInfo loginInfo) throws Exception {

      if (StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())) {
         customerVO.setSalesConsultantNo(loginInfo.getUserCode());
      }
      customerVO.setPartnerCode(loginInfo.getPartnerCode());
      return customerService.todayCustomerList(customerVO);
   }

   @Override
   public List listByVo(CustomerVO customerVO, LoginInfo loginInfo) {
      if (loginInfo.getPartner() != null) {
         PartnerVO partnerVO = JSONObject.parseObject(JSONObject.toJSONString(loginInfo.getPartner()), PartnerVO.class);
         customerVO.setPartnerCode(partnerVO.getPartnerCode());
         if (loginInfo.getStaff() != null) {

            if (DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())) {
               customerVO.setSalesConsultantNo(loginInfo.getUserCode());
            }

            if (DictConstant.USER_ROLE_MANAGER.equals(loginInfo.getRoleCode())) {
               customerVO.setSalesConsultantNo("");
            }
            /*
            if ("ZW0801".equals(staffVO.getPositionCode())) {//销售顾问
               customerVO.setSalesConsultantNo(loginInfo.getUserCode());
            }
            if ("ZW0802".equals(staffVO.getPositionCode())) {//销售顾问销售经理
               customerVO.setSalesConsultantNo("");
            }*/
         }
      } else {
         customerVO.setPartnerCode("");
         customerVO.setSalesConsultantNo("");
      }
      return customerService.listByVo(customerVO);
   }

   @Override
   public CustomerVO getByPhone(String customerMobile, String partnerCode) {
      CustomerVO vo = customerService.getByPhone(customerMobile, partnerCode);
      return vo;
   }

   @Override
   public void saveOrUpdate(CustomerVO v1) {
      Customer t = new Customer();
      BeanUtils.copyProperties(v1, t);
      customerService.save(t);
   }

   @Override
   public CustomerVO queryCustomerByCustomerNo(String customerNo, String partnerCode) {
      QueryWrapper qw = new QueryWrapper();
      qw.eq("CUSTOMER_NO",customerNo);
      qw.eq("PARTNER_CODE",partnerCode);
      qw.eq("SOURCE","2");

      Customer customer = customerService.getOne(qw);

      if(customer == null)
         return null;

      CustomerVO customerVO = new CustomerVO();

      BeanUtils.copyProperties(customer,customerVO);

      return customerVO;
   }

   @Override
   public void updateOrSave(CustomerVO customerVO) {
      Customer t = new Customer();
      BeanUtils.copyProperties(customerVO, t);
      customerService.saveOrUpdate(t);
   }

   @Override
   public void updateByCustomerNo(CustomerVO customerVO) {

      Customer customer = new Customer();
      BeanUtils.copyProperties(customerVO,customer);
      QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();

      HashMap<String, Object> map = new HashMap<>();
      map.put("CUSTOMER_NO",customerVO.getCustomerNo());
      map.put("PARTNER_CODE",customerVO.getPartnerCode());
      queryWrapper.allEq(map);
      customerService.update(customer,queryWrapper);
   }

   @Override
   public PageInfo<CustomerVO> pageByOem(CustomerVO customerVO, Integer pageNum, Integer pageSize, LoginInfo loginInfo) {
      return customerService.pageByOem(customerVO, pageNum, pageSize);
   }


   @Override
   public List<CustomerVO> allList(CustomerVO customerVO, LoginInfo loginInfo) throws Exception {
      customerVO.setPartnerCode(loginInfo.getPartnerCode());
      // 非总经理、非销售经理则按登录账号查询
      if (StringUtils.isNotEmpty(loginInfo.getRoleCode()) && !DictConstant.USER_ROLE_MANAGER
          .equals(loginInfo.getRoleCode()) && !DictConstant.USER_ROLE_PARTNER_MANAGER
          .equals(loginInfo.getRoleCode())) {
         customerVO.setSalesConsultantNo(loginInfo.getUserCode());
      }
      customerVO.setCustCreateTime(new Date());
      return customerService.allList(customerVO);
   }

   /**
    * URM -> PMS
    * 客户信息同步
    *
    * @param customerVOURMs
    * @return
    */
   @Override
   public ApiResult sycnCustomerInfoFromUrm(List<CustomerVOURM> customerVOURMs) throws InvocationTargetException, IllegalAccessException, InterruptedException {
      if (customerVOURMs != null && customerVOURMs.size() > 0) {
         for (CustomerVOURM customerVOURM : customerVOURMs) {
            if (StringUtils.isEmpty(customerVOURM.getMobile())) return ResponseUtil.fail(-1,"手机号为空");
            if (customerVOURM.getMobile().length() !=11) return ResponseUtil.fail(-1,"手机号错误");
            if (customerVOURM.getId()==null) return ResponseUtil.fail(-1,"用户id为空");
            CustomerVO customerVO = setCustomerVOFromURM(customerVOURM);
            Customer customer = new Customer();
            BeanUtils.copyProperties(customerVO,customer);
            if (StringUtils.isEmpty(customerVO.getPartnerCode())){
//            saveCustomerInfo(customerVO, new LoginInfo());
               QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
               queryWrapper.eq("CUSTOMER_NO",customerVO.getCustomerNo());
               Thread.sleep(2000);
               int count = customerService.count(queryWrapper);
                if (count != 0) {
                   customer.setCustStatus(null);
                   customer.setSource(null);
                    customerService.update(customer, queryWrapper);
                } else if (count == 0) {
                   customer.setSource(3);
                    customerService.save(customer);
                }
            }else {
               QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
               HashMap<String, Object> map = new HashMap<>();
               map.put("CUSTOMER_NO",customerVO.getCustomerNo());
               map.put("PARTNER_CODE",customerVO.getPartnerCode());
               queryWrapper.allEq(map);
               int count = customerService.count(queryWrapper);
               if (count==1){
                  customer.setCustStatus(null);
                  customer.setSource(null);
                  customerService.update(customer,queryWrapper);
               }else if (count==0){
                  customer.setSource(3);
                  customerService.save(customer);
               }
            }

         }
      }
      return ResponseUtil.ok();
   }

   private CustomerVO setCustomerVOFromURM(CustomerVOURM customerVOURM) {
      CustomerVO customerVO = new CustomerVO();
      if (customerVOURM.getId() != null) {
         customerVO.setCustomerNo(String.valueOf(customerVOURM.getId()));//用户id
      }
      customerVO.setPhone(customerVOURM.getMobile());//手机号
      customerVO.setName(customerVOURM.getName());//姓名
      if (customerVOURM.getSex() != null) {
         customerVO.setSex(String.valueOf(customerVOURM.getSex()));//性别 0：未知，1：男，2：女
      }
//      customerVO.setPartnerCode(customerVOURM.getAgency());//供应商
      customerVO.setSalesConsultantNo(customerVOURM.getSalesConsultant());//销售顾问
      if (customerVOURM.getBigRegion() != null) {
         customerVO.setBigRegion(String.valueOf(customerVOURM.getBigRegion()));//大区
      }
      customerVO.setProvince(customerVOURM.getRegProvince());//省
      customerVO.setCity(customerVOURM.getRegCity());//市
      customerVO.setRegion(customerVOURM.getRegStrict());//区
      customerVO.setAddr(customerVOURM.getAddress());//详细地址
      if (customerVOURM.getUserType() != null) {
         customerVO.setCustomerType(String.valueOf(customerVOURM.getUserType()));//用户类型
      }
      customerVO.setIntentionLev(customerVOURM.getIntentionLevel());//意向等级
      customerVO.setProfession(customerVOURM.getProfession());//行业
      customerVO.setDuty(customerVOURM.getDuty());//职位
      customerVO.setEducation(customerVOURM.getEducation());//学历 0：未识别，1：高中，2：专科，3：本科，4：硕士，5：博士，6：其他
      if (StringUtils.isNotEmpty(customerVOURM.getAnnualIncome())  ) {
         customerVO.setAnnualIncome(new BigDecimal(customerVOURM.getAnnualIncome()));//年收入
      }
      customerVO.setMaritalStatus(customerVOURM.getMaritalStatus());//婚姻状态 0：未识别，1：已婚，2：未婚
      customerVO.setChildNum(customerVOURM.getChildNum());//孩子数量
      customerVO.setChild1Age(customerVOURM.getChild1Age());//子女1的年龄
      customerVO.setChild2Age(customerVOURM.getChild2Age());//子女1的年龄
      customerVO.setPurchaseIntention(customerVOURM.getPurchaseIntention());//购买意向
      customerVO.setVehiclePersonnelStructure(customerVOURM.getVehiclePersonnelStructure());//用车人员结构
      customerVO.setVehicleScene(customerVOURM.getVehicleScene());//用车场景
      customerVO.setDriver(customerVOURM.getDriver());//驾驶人 0, 未识别 1, 自己 2, 伴侣 3, 父母 4, 其他
      customerVO.setIntentionalPurchasePrice(customerVOURM.getIntentionalPurchasePrice());//意向购车价格
      customerVO.setServiceSensitivity(customerVOURM.getServiceSensitivity());//服务敏感度 分为1-10等级
      customerVO.setVehicleKnowledgeProfessional(customerVOURM.getVehicleKnowledgeProfessional());//汽车知识专业度 分为1-10等级
      customerVO.setCarConcerns(customerVOURM.getCarConcerns());//关注点
      customerVO.setFamilyVehiclesNum(customerVOURM.getFamilyVehiclesNum());//家庭车辆数量
      customerVO.setFamilyVehicleBrand(customerVOURM.getFamilyVehicleBrand());//家庭车辆品牌，多个使用逗号隔开
      customerVO.setUserSource1(customerVOURM.getUserSource_1());
      customerVO.setUserSource2(customerVOURM.getUserSource_2());
      customerVO.setUserSource3(customerVOURM.getUserSource_3());
//      customerVO.setSource(3);
      customerVO.setCustStatus(4);
      return customerVO;
   }
}
